<?php

/**
 * Created by PhpStorm.
 * Author: ls
 * Time: 2023/9/20 10:34
 * Desc: 订单
 */
class Service_Api_Order extends Contract_Api_Order
{

    public function list(int $mid, array $params = array()): array
    {
        /**
         * @var $status
         * @var $type_id
         * @var $page
         * @var $pagesize
         */
        extract($params);
        //排除积分商城.扫码收款订单
        $exclude_typeids = [15];
        $builder = DB::select()
                     ->from('member_order')
                     ->where('memberid', '=', $mid)
                     ->and_where('typeid', 'not in', $exclude_typeids)
                     ->and_where('pid', '=', 0);

        //订单状态
        if (isset($params['status'])) {
            $builder->and_where('status', '=', $status);
            if ($status == 5) { // 未点评的
                $builder->and_where('ispinlun', '=', 0);
            }
        }

        //订单类型
        if (isset($params['type_id'])) {
            $builder->and_where('typeid', '=', $type_id);
        }

        //隐藏正在进行的拼团订单
        /*if (St_Functions::is_normal_app_install('together')) {
            $invalid_ordersn = Model_Together_Order::get_invalid_ordersn($mid);
            if (!empty($invalid_ordersn)) {
                $builder->and_where('ordersn', 'not in', DB::expr(sprintf("(%s)", implode(',', $invalid_ordersn))));
            }
        }*/

        $total = $builder->execute()->count();

        $offset = St_Page::offset($page, $pagesize);
        $list   = $builder->limit($pagesize)
                          ->offset($offset)
                          ->order_by('id', 'desc')
                          ->execute()
                          ->as_array();

        $filter_keys = array(
            'id', 'status', 'ordersn', 'litpic', 'productname', 'suit_name', 'usedate', 'price',
            'refund_restriction', 'ispinlun', 'productautoid', 'typeid', 'is_perfect');

        foreach ($list as &$v) {
            //私人定制，订单是否完善
            if($v['typeid'] == 14){
                $v['is_perfect'] = DB::select()->from('customize')->where('id','=',$v['productautoid'])->execute()->get('is_perfect');
            }
            // 订单金额
            $total_info = Model_Member_Order_Compute::get_order_price($v['id']);
            $v['price'] = floatval(number_format($total_info['pay_price'], 2, '.', ''));
            //产品缩略图
            $v['litpic'] = $this->img_url($v['litpic'], 258, 175);
            //分割订单产品名称h
            $tempArr          = array_filter(preg_split('`[\(\)]`', $v['productname']));
            $v['subname']     = count($tempArr) > 1 ? $tempArr[count($tempArr) - 1] : '';
            $v['productname'] = str_replace("({$v['subname']})", '', $v['productname']);
            list($productname, $ticket_type_name) = explode(' -- ', $v['productname']);
            $v['productname'] = $productname;
            $v = $this->filter_data($filter_keys, $v);
        }

        return array('total' => $total, 'list' => $list);
    }

    public function detail(int $mid, int $id): array
    {
        $order = Model_Api_V2_Order::get_detail($id, $mid);
        if (!$order) {
            throw new Exception('订单不存在');
        }

        if (St_Functions::is_normal_app_install('memberdiscount')) {
            if ($order['paytype'] == 2) {
                $order['member_discount_price'] = Model_Discount::get_order_discount($id);
            }
        }

        $order['totalprice'] = $order['totalprice'] - $order['iscoupon']['cmoney'] - $order['jifentprice'] - $order['platform_discount'] - $order['envelope_price'];

        //航线附加产品信息
        if ($order['typeid'] == '104') {
            if (St_Functions::is_normal_app_install('system_ship_line')) {
                $attach_info = Model_Api_V2_Ship::order_attach($order);
                $order       = array_merge($order, $attach_info);
            }
        }

        $order['card_pay'] = false;
        if (St_Functions::is_normal_app_install('system_card')) {
            if ($order['typeid'] == 198) {
                $order['card_member'] = Model_Api_V2_Card::order_detail($order);
            }
            $is_exist          = DB::select()
                                   ->from('card_member_reservation_record')
                                   ->where('order_sn', '=', $order['ordersn'])
                                   ->execute()
                                   ->current();
            $order['card_pay'] = (bool)$is_exist;
        }

        $order['wallet_pay'] = 0;
        if (St_Functions::is_normal_app_install('system_wallet')) {
            $wallet_log = DB::select()->from('wallet_log')
                            ->where('order_sn', '=', $order['ordersn'])
                            ->and_where('type', '=', 3)
                            ->execute()->current();
            if($wallet_log){
                $order['wallet_pay'] = $wallet_log['use_amount'];
            }
        }

        $order['addtime'] = $order['addtime'] ? date('Y-m-d H:i:s', $order['addtime']) : '';
        $order['paytime'] = $order['paytime'] ? date('Y-m-d H:i:s', $order['paytime']) : '';
        $order['apply_time'] = null;
        $order['refund_time'] = null;
        if($order['status'] == 4){
            $date = DB::select()->from('member_order_refund')->where('ordersn','=',$order['ordersn'])->and_where('status','=',1)->execute()->current();
            $order['apply_time'] = $date['addtime'] ? date('Y-m-d H:i:s', $date['addtime']) : '';
            $order['refund_time'] = $date['modtime'] ? date('Y-m-d H:i:s', $date['modtime']) : '';
        }
        if($order['status'] == 6){
            $addtime = DB::select()->from('member_order_refund')->where('ordersn','=',$order['ordersn'])->and_where('status','=',0)->execute()->get('addtime');
            $order['apply_time'] = $addtime ? date('Y-m-d H:i:s', $addtime) : '';
        }

        //判断是否是拼团订单
        if(St_Functions::is_normal_app_install('together')){
            $together_order= DB::select()->from('together_order')->where('ordersn','=',$order['ordersn'])->execute()->current();
            if($together_order){
                $together_id = $together_order['together_id'];
                $special = DB::select('special')->from('together')->where('id','=',$together_id)->execute()->get('special');
                $join_nums  = Model_Together_Order::count_join_num([$together_order['join_id']]);
                $num = $join_nums[$together_order['join_id']];

                $join = DB::select('together_num')->from('together_join')->where('id','=',$together_order['join_id'])->execute()->current();

                if($special==1 && $num<$join['together_num']){//需要满足参团人数，才可核销
                    $order['eticketno']=null;
                }
            }
        }


        if($order['typeid']==3&&$order['self_pickup']){
            $order['self_pickup'] = json_decode($order['self_pickup'],true);
        }

        unset($order['memberid']);
        unset($order['webid']);
        unset($order['productaid']);
        unset($order['member_info']['id']);

        return $order;
    }

    function get_traveller_list(int $mid, int $id): array
    {
        $order = Model_Member_Order::get_order_detail($id, $mid);

        if (!$order) {
            throw new Exception('订单不存在');
        }

        if ($order['typeid'] == 114) {
            $list = DB::select()
                      ->from('outdoor_tourer')
                      ->where('orderid', '=', $id)
                      ->execute()
                      ->as_array();
        } else {
            $list = DB::select()
                      ->from('member_order_tourer')
                      ->where('orderid', '=', $id)
                      ->execute()
                      ->as_array();
        }

        foreach ($list as &$v) {
            unset($v['id']);
            $v['en_first_name']          = $v['en_first_name'] ?: '';
            $v['en_last_name']           = $v['en_last_name'] ?: '';
            $v['nationality']            = $v['nationality'] ?: '';
            $v['cardnumber_expire_date'] = $v['cardnumber_expire_date'] ?: '';
            $v['birth']                  = $v['birth'] ?: '';
        }

        return $list;
    }

    public function cancel_order(int $mid, string $ordersn): array    {
        //查询订单信息
        $order = Model_Member_Order::get_order_by_ordersn($ordersn, $mid);
        if (!$order) {
            throw new Exception('订单不存在');
        }

        if ($order['ispay'] == 1) {
            throw new Exception('已支付的订单不可取消');
        } else {
            if (!in_array($order['status'], [0, 1])) {
                throw new Exception('订单状态不支持退订');
            }
        }

        // 取消订单
        $data = Model_Api_V2_Order::cancel_order($ordersn);
        if (isset($data['msg']) && $data['msg'] == 1) {
            return array();
        } else {
            throw new Exception('订单取消失败,请重试');
        }
    }

    public function consume_order(int $mid, int $id): array
    {
        $order = ORM::factory('member_order')
                    ->where('id', '=', $id)
                    ->where('memberid', '=', $mid)
                    ->find();

        if (!$order->loaded()) {
            throw new Exception('订单不存在');
        }


        //如果是拼团订单
        $together_order= DB::select()->from('together_order')->where('ordersn','=',$order->ordersn)->execute()->current();
        if($together_order){
            $together_id = $together_order['together_id'];
            $special = DB::select('special')->from('together')->where('id','=',$together_id)->execute()->get('special');
            $join_nums  = Model_Together_Order::count_join_num([$together_order['join_id']]);
            $num = $join_nums[$together_order['join_id']];

            $join = DB::select('together_num')->from('together_join')->where('id','=',$together_order['join_id'])->execute()->current();

            if($special==1 && $num<$join['together_num']){//需要满足参团人数，才可核销
                throw new Exception('未成团无法消费');
            }
        }

        if ($order->status != 2 && $order->status != 8) {
            throw new Exception('订单状态不支持消费，请重试');
        }

        $order->consumetime = time();
        $order->status      = 5;
        $order->save();
        if (!$order->saved()) {
            throw new Exception('订单消费失败,请重试');
        }
        $order->reload();

        $order  = $order->as_array();
        $model  = Model_Api_V2_Pub::get_model_class_name($order['typeid']);
        $status = Model_Member_Order::back_order_status_changed(2, $order, $model);
        if (!$status) {
            throw new Exception('订单消费失败');
        }

        return array();
    }

    function express_confirm(int $mid, int $id): array
    {
        $order = ORM::factory('member_order')
                    ->where('id', '=', $id)
                    ->and_where('memberid', '=', $mid)
                    ->find();

        if (!$order->loaded()) {
            throw new Exception('订单不存在');
        }

        if ($order->status != '8') {
            throw new Exception('订单状态不支持该操作');
        }

        if (!in_array($order->typeid, array(8, 21, 107))) {
            throw new Exception('产品不支持该操作');
        }

        switch ($order->typeid) {
            case 8:
                $mode_str = 'Model_Visa';
                break;
            case 21:
                $mode_str = 'Model_Malls';
                break;
            case 107:
                $mode_str = 'Model_Integral';
                break;
            default:
                $mode_str = '';
        }

        $order->status = 5;
        $order->save();

        if ($order->saved()) {
            $order->reload();
            $order = $order->as_array();
            Model_Member_Order::back_order_status_changed(8, $order, $mode_str);
            return array();
        } else {
            throw new Exception('订单确认失败');
        }
    }

    public function get_contract_content(int $mid, int $id): array
    {
        $order = Model_Member_Order::get_order_detail($id, $mid);
        if (!$order) {
            throw new Exception('订单不存在');
        }

        if (!$order['contract_id']) {
            throw new Exception('未设置合同');
        }


        $contract = DB::select()
                      ->from('contract')
                      ->where('id', '=', $order['contract_id'])
                      ->execute()
                      ->current();
        if (!$contract) {
            throw new Exception('合同不存在');
        }

        //自定义合同
        if (!$contract['type'] || $contract['type'] == 1) {
            $data['title'] = $contract['title'];
            $url           = St_Functions::get_web_url(0) . '/contract/view/ordersn/' . $order['ordersn'] . '/headhidden/1';
            $content       = St_Network::http($url);
            $dir           = BASEPATH . '/uploads/contract/';
            if (!file_exists($dir)) {
                mkdir($dir, 0777);
            }
            $filename = time() . '.html';
            file_put_contents($dir . $filename, $content);
            $download_link     = St_Functions::get_main_host() . '/uploads/contract/' . $filename;
            $data['content']   = $content;
            $data['url']       = $download_link;
            $data['extension'] = 'html';
            return $data;
        } else {
            //12301合同
            if ($contract['type'] == 2) {
                $contracts_up = DB::select()
                                  ->from('contract_supervise')
                                  ->where('order_id', '=', $id)
                                  ->execute()
                                  ->current();
                if ($contracts_up) {
                    $url = $contracts_up['fileURL'];
                    $str = file_get_contents($url);
                    file_put_contents(BASEPATH . '/uploads/contract/12301.pdf', $str);
                    $data['title']     = $contracts_up['contractnName'];
                    $data['content']   = '';
                    $data['url']       = St_Functions::get_main_host() . '/uploads/contract/12301.pdf';
                    $data['extension'] = 'pdf';
                } else {
                    $data['title']     = '';
                    $data['content']   = '';
                    $data['url']       = '';
                    $data['extension'] = '';
                }
                return $data;
            } else {
                throw new Exception('合同不存在');
            }
        }
    }

    public function get_status(int $mid, int $id): array
    {
        $order = Model_Member_Order::get_order_detail($id, $mid);
        if (!$order) {
            throw new Exception('订单不存在');
        }

        return $this->filter_data(array('id', 'ordersn', 'status', 'ispay', 'paytime'), $order);
    }

    public function get_express_progress(int $mid, string $ordersn): array
    {
        $order = Model_Member_Order::get_order_by_ordersn($ordersn, $mid);
        if (!$order) {
            throw new Exception('订单不存在');
        }

        //物流单号信息
        $express = DB::select('express_code', 'express_company_name', 'receive_people', 'receive_link')
                     ->from('malls_order_express')
                     ->where('ordersn', '=', $ordersn)
                     ->execute()
                     ->current();
        if ($express) {
            $express_progress = DB::select()
                                  ->from('express_info')
                                  ->where('express_sn', '=', $express['express_code'])
                                  ->execute()
                                  ->current();
            if ($express_progress) {
                $express_progress['context'] = json_decode($express_progress['context'], true);
            }
        }

        return array(
            'expressSn' => $express,
            'expressProgress' => isset($express_progress) && $express_progress ? $express_progress : null,
        );
    }
}
